<template>
    <Modal
        v-model="isAddModalVisible"
        :loading="true"
        :width="800"
        title="编辑租客信息">

        <Row :guttle="40">
            <Col span="16">
                <Form ref="addForm" :model="formItem" :rules="ruleValidate" :label-width="110">
                    <FormItem label="租客姓名" prop="name">
                        <Input v-model="formItem.name" :maxlength="20" placeholder="租客姓名"/>
                    </FormItem>
                    <FormItem label="租客电话" prop="phone">
                        <Input v-model="formItem.phone" :maxlength="11" placeholder="租客电话" :disabled="true">
                        </Input>
                    </FormItem>
                    <FormItem label="身份证号" prop="id_card">
                        <Input v-model="formItem.id_card" :maxlength="18" placeholder="身份证号" :disabled="isDisabledIdCard"></Input>
                    </FormItem>

                     <FormItem label="租客标签" prop="tenant_tag_id">
                        <Select v-model="formItem.tenant_tag_id">
                            <Option v-for="item in tenantTags" :value="item.id" :key="item.id">{{ item.name }}</Option>
                        </Select>
                    </FormItem>
                </Form>
            </Col>

            <Col span="8" v-if="hasFaceAccessPermission">
                <take-photo v-model="face_file_id" :isclearPreviewImg="isclearPreviewImg" :img="imgUrl"/>
            </Col>
        </Row>

         <div slot="footer">
            <Button type="ghost" size="large" @click="cancelAddRenter('addForm')">取消</Button>
            <Button type="primary" :loading = "isLoadig" size="large" @click="confirmAddRenter('addForm')">保存</Button>
        </div>
    </Modal>
</template>

<script>
import validate from '@/libs/validate'
import { http, api } from '@/libs/http'
import { CountryCodes } from '@/libs/const'
import takePhoto from '../tenancy-device/take-photo.vue'
import { mapState } from 'vuex'
export default {
  data () {
    return {
      isLoadig: false, // 是否正在发请求
      face_file_id: '', // 人脸face_id
      isclearPreviewImg: false, // 是否清除照片
      tenantTags: [], // 租客标签
      CountryCodes,
      imgUrl: '', // 租客图片Url
      formItem: {
        // 添加租客参数
        name: '',
        phone: '',
        id_card: '',
        // country_code:'86',
        tenant_tag_id: ''
      },
      ruleValidate: {
        name: [
          {
            required: true,
            message: '请输入租客姓名',
            trigger: 'change'
          }
        ],
        phone: [
          {
            required: true,
            message: '请输入租客手机号',
            trigger: 'change'
          },
          { validator: validate.validPhone, trigger: 'change' }
        ],
        tenant_tag_id: [
          {
            required: false
          }
        ],
        id_card: [
          {
            required: false,
            message: '请输入身份证号码',
            trigger: 'change'
          }
        ]
      }
    }
  },

  props: {
    isShow: { // 控制弹窗是否显示
      type: Boolean,
      required: true
    },

    value: {
      type: [Object],
      default: Object
    }
  },

  computed: {
    ...mapState({
      hasFaceAccessPermission: state => state.user.hasFaceAccessPermission
    }),
    isAddModalVisible: { // 控制弹窗是否显示
      set (value) {
        this.$emit('update:isShow', value)
      },

      get () {
        return this.isShow
      }
    },

    isDisabledIdCard () {
      const { id_card } = this.value

      return !!id_card
    }
  },

  components: {
    takePhoto
  },

  watch: {
    isAddModalVisible (value) {
      if (value) {
        this.isclearPreviewImg = true
        this.getTenantTag()
        this.getRenterPic()
      } else {
        this.isclearPreviewImg = false
        this.reset()
      }
    },

    value (n) { // 构造数据
      this.reset()
    }
  },

  methods: {
    /**
        * 获取租客图片
        */
    async getRenterPic () {
      const { face_file_id } = this.value

      if (face_file_id) {
        try {
          const imgUrl = await http.fetch(this, api.face_photo_show, [face_file_id])

          this.imgUrl = imgUrl // 图片预览图链接
        } catch (error) {
          console.log('err', error)
        }
      }
    },

    reset () {
      if (Object.keys(this.value).length) {
        const { name, id_card, phone, tenant_tag_id, face_file_id } = this.value

        this.formItem = {
          name,
          id_card,
          phone,
          tenant_tag_id
        }

        this.face_file_id = face_file_id
      }
    },

    /**
        * 获取租客标签
        */
    async getTenantTag () {
      const { rows } = await http.fetch(this, api.tenant_tags_get)

      this.tenantTags = rows
    },

    cancelAddRenter (name) {
      // 取消添加租客
      // this.resetForm(name);
      this.isAddModalVisible = false
    },

    validateIdCard (value) {
      const reg = /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)/

      return reg.test(value)
    },

    confirmAddRenter (name) {
      this.$refs[name].validate(valid => {
        if (valid) {
          const params = this.formItem
          let { tenant_tag_id, id_card } = this.formItem

          if (this.face_file_id) {
            params.face_file_id = this.face_file_id
          }

          if (!tenant_tag_id) {
            delete params.tenant_tag_id
          }

          if (!id_card) {
            delete params.id_card
          } else {
            const flag = this.validateIdCard(id_card) // 检验身份证号

            if (!flag) {
              this.$Message.error('请输入正确的身份证号码!')
              return
            }
          }

          delete params.phone
          this.isLoadig = true
          http.request(this, api.tenant_update, [this.value.id], params, res => {
            if (res) {
              this.isLoadig = false
              this.$Message.success('修改租客信息成功!')
              this.isAddModalVisible = false
              this.$emit('refresh') // 刷新租客详情
            } else {
              this.isLoadig = false
            }
          })
        } else {
          this.$Message.error('请完整填写表单数据!')
        }
      })
    }
  }
}
</script>
<style lang='stylus'>
</style>